package util;

import java.io.Reader;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.*;

public class MyBatisUtil {

    private static SqlSessionFactory sqlMapper;

    static {
        try {
            Reader reader = Resources.getResourceAsReader("MyBatisConfig.xml");
            sqlMapper = new SqlSessionFactoryBuilder().build(reader);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public static SqlSession getSession() {
        return sqlMapper.openSession();
    }
    public static Object selectOne(String methodName, Object param) {
        SqlSession session = MyBatisUtil.getSession();
        try {
            return session.selectOne(methodName, param);
        } finally {
            session.close();
        }
    }

    public static Object selectList(String methodName, Object param) {
        SqlSession session = MyBatisUtil.getSession();
        try {
            return session.selectList(methodName, param);
        } finally {
            session.close();
        }
    }

    public static void insert(String methodName, Object param) {
        SqlSession session = MyBatisUtil.getSession();
        try {
            session.insert(methodName, param);
            session.commit();
        } finally {
            session.close();
        }
    }


    public static void delete(String methodName, Object param) {
        SqlSession session = MyBatisUtil.getSession();
        try {
            session.delete(methodName, param);
            session.commit();
        } finally {
            session.close();
        }
    }
    public static void update(String methodName, Object param) {
        SqlSession session = MyBatisUtil.getSession();
        try {
            session.update(methodName, param);
            session.commit();
        } finally {
            session.close();
        }
    }

}
